package light.head.framework.utils;

public class AesUtils {
	/**
	 * 简化版AES加密
	 * @param 要加密的byte数组
	 * @return 加密后的byte数组
	 * @author 简航 创建日期 2009-08-05 15:46:40
	 */
	public static byte[] teaEncrypt(byte[] pbuf, int[] key) {
		int[] k = key.clone();
		k[2] = k[0] + k[1];
		k[3] = k[0] - k[1];

		int nLength = pbuf.length / 4;
		int[] v = DisplacementUtils.bytes2ints_intercept(pbuf);

		int n = nLength - 1;
		if (n >= 1) {
			int z = v[n], y = v[0], delta = 0x9E3779B9, sum = 0, e;
			int i, q = 6 + 52 / (n + 1);

			while (q-- > 0) {
				sum = (sum + delta);
				e = sum >> 2 & 3;
				for (i = 0; i < n; i++) {
					y = v[i + 1];
					v[i] += ((z >>> 4 ^ y << 2) + (y >>> 3 ^ z << 4))
							^ ((sum ^ y) + (k[(i & 3) ^ e] ^ z));

					z = v[i];
				}
				y = v[0];
				v[n] += ((z >>> 4 ^ y << 2) + (y >>> 3 ^ z << 4))
						^ ((sum ^ y) + (k[(i & 3) ^ e] ^ z));
				z = v[n];
			}
		}

		DisplacementUtils.ints2bytes(v, pbuf);

		if (nLength <= 1 || pbuf.length % 4 != 0) {
			int nr = nLength > 1 ? nLength * 4 : 0;

			for (int i = nr; i < pbuf.length; i++) {
				byte[] kb = DisplacementUtils.int2bytes(k[i % 4]);
				pbuf[i] ^= kb[0];
			}
		}
		return pbuf;
	}

	/**
	 * 简化版AES解密
	 * @param 要解密的byte数组
	 * @return 解密后的byte数组
	 * @author 简航 创建日期 2009-08-05 15:47:07
	 */
	public static byte[] teaDecrypt(byte[] pbuf, int[] TeaKey) {

		int[] v = DisplacementUtils.bytes2ints_intercept(pbuf);

		int nLength = pbuf.length / 4;
		int[] k = TeaKey;
		k[2] = k[0] + k[1];
		k[3] = k[0] - k[1];

		int n = nLength - 1;
		if (n >= 1) {
			int z = v[n], y = v[0], delta = 0x9E3779B9, sum, e;
			int i, q = 6 + 52 / (n + 1);
			sum = q * delta;

			while (sum != 0) {
				e = sum >> 2 & 3;
				for (i = n; i > 0; i--) {
					z = v[i - 1];
					v[i] -= ((z >>> 4 ^ y << 2) + (y >>> 3 ^ z << 4))
							^ ((sum ^ y) + (k[(i & 3) ^ e] ^ z));
					y = v[i];
				}
				z = v[n];
				v[0] -= ((z >>> 4 ^ y << 2) + (y >>> 3 ^ z << 4))
						^ ((sum ^ y) + (k[(i & 3) ^ e] ^ z));
				y = v[0];
				sum = sum - delta;
			}

		}
		
		DisplacementUtils.ints2bytes(v, pbuf);

		if (nLength <= 1 || pbuf.length % 4 != 0) {
			int nr = nLength > 1 ? nLength * 4 : 0;

			for (int i = nr; i < pbuf.length; i++) {
				byte[] kb = DisplacementUtils.intToByte(k[i % 4]);
				pbuf[i] ^= kb[0];
			}
		}
		return pbuf;
	}
}
